package com.hxt.framework.dubbo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.hxt.framework.manager.RetCodeManager;
import com.hxt.framework.manager.TxIdManager;
import com.hxt.framework.msg.RequestMsg;
import com.hxt.framework.msg.ResponseMsg;
import com.hxt.framework.utils.DateUtil;
import com.hxt.framework.utils.DbUtil;
import com.hxt.framework.utils.JsonUtil;
import com.hxt.framework.utils.SpringUtils;

@Service("iDubboService")
public class DubboServiceImpl implements IDubboService {

	@Override
	public DubboOut doPost(DubboIn dubboIn) {
		String txid = dubboIn.getTxId();
		DubboOut dubboOut = new DubboOut();
		MethodBean methodBean = TxIdManager.getGlobal().getMethodBean(txid.toUpperCase());
		if (null == methodBean) {
			// 返回失败对象
			ResponseMsg<?> resp = new ResponseMsg<>();
			RetCodeManager.getGlobal().setErroCode(resp, "SYS-105");
			dubboOut.setParam(JsonUtil.writeValueAsString(resp));
		} else {
			try {
				Class<?> serviceObj = Class.forName(methodBean.getClassName());
				System.out.println("-------------------------" + txid + "  请求-------------------------");

				System.out.println(JsonUtil.writerWithDefaultPrettyPrinter(
						JsonUtil.deserializeRequstVo(dubboIn.getParam(), Object.class)));
				// 反序列化参数
				RequestMsg<?> reqObj = (RequestMsg<?>) JsonUtil.deserializeRequstVo(dubboIn.getParam(),
						Class.forName(methodBean.getParamClassName()), Class.forName(methodBean.getReqActualType()));
				reqObj.setTxId(txid);

				ResponseMsg<?> resp = (ResponseMsg<?>) invokeMethod(serviceObj, methodBean.getMethodName(), reqObj);
				if (resp == null)
					resp = new ResponseMsg<>();

				if (ObjectUtils.isEmpty(reqObj.getReqSeq()))
					reqObj.setReqSeq(String.valueOf(DateUtil.getToday()));
				resp.setReqSeq(reqObj.getReqSeq());
				dubboOut.setParam(JsonUtil.writeValueAsString(resp));

				System.out.println("------------------------- " + txid + "  返回-------------------------");

//				System.out.println(JsonUtil.writerWithDefaultPrettyPrinter(
//						JsonUtil.deserializeRequstVo(JsonUtil.writeValueAsString(resp), Object.class)));

				System.out.println(JsonUtil.writeValueAsString(resp));

				System.out.println();

			} catch (Exception e) {
				e.printStackTrace();

			} finally {
				StringBuffer sb = new StringBuffer();
				sb.append("insert into user_operate_log(ReqUrl,ReqParam,ReqTime) values('").append(txid).append("','")
						.append(dubboIn.getParam()).append("',").append(DateUtil.getToday()).append(");");
				System.out.println(sb.toString());
				DbUtil.insert(sb.toString());
			}

		}
		return dubboOut;
	}

	/**
	 * 
	 * @Title: invokeMethod
	 * @Description: 反射对应服务类
	 * @param serviceObj 服务类class
	 * @param methodName 方法名称
	 * @param reqObj     请求参数bean
	 * @return
	 * @throws Exception
	 * @return: Object
	 */
	public static <T> Object invokeMethod(Class<?> serviceObj, String methodName, Object reqObj) throws Exception {
		try {
			Method f = serviceObj.getMethod(methodName.toLowerCase(), new Class[] { reqObj.getClass() });// 方法名称、方法参数类型；多个参数类型形式如，new
			if (!f.isAccessible()) {
				f.setAccessible(true);
			}
			Object obj = SpringUtils.getBean(serviceObj);
			return f.invoke(obj, reqObj);
		} catch (SecurityException e) {
			e.printStackTrace();
			throw new Exception(e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			throw new Exception(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new Exception(e.getMessage(), e);
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			throw new Exception(e.getMessage(), e);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			throw new Exception("接口" + serviceObj.getName() + " 没有找到方法 " + methodName + "()", e);
		}
	}

}
